package org.example.strategy.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.constant.AuthConstants;
import org.example.domain.LoginSysUser;
import org.example.mapper.LoginSysUserMapper;
import org.example.model.SecurityUser;
import org.example.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Set;


@Service(AuthConstants.LOGIN_TYPE_USER)
public class SysUserLoginStrategy implements LoginStrategy {

    @Autowired
    private LoginSysUserMapper loginSysUserMapper;

    @Override
    public UserDetails realLogin(String username) {

        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(new QueryWrapper<LoginSysUser>()
                .eq("username", username)
        );

        if (ObjectUtil.isNotEmpty(loginSysUser)){
            //根据用户标识查询用户权限
            Set<String> perms =loginSysUserMapper.selectPermsByUserId(loginSysUser.getUserId());

            SecurityUser securityUser =new SecurityUser();
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setStatus(loginSysUser.getStatus());
            securityUser.setShopId(loginSysUser.getShopId());
            securityUser.setLoginType(AuthConstants.LOGIN_TYPE_USER);
            if (CollectionUtil.isNotEmpty(perms) && perms.size() != 0){
                securityUser.setPerms(perms);
            }

            return securityUser;
        }
        return null;
    }
}
